import React from 'react';
import { Toast } from 'antd-mobile';
import "./index.scss"
import { getAreaCityApi, getAreaHotApi } from "../../api/axios.js";
import formatCityData from "../../utils/formatCityData";
import { getCurrentCity } from "../../utils/getCurrentCity";

import { List, AutoSizer } from 'react-virtualized';
// 导入封装好的 NavHeader 组件
import NavHeader from '../../components/NavHeader'


// 定义常量
const TITLE_HEIGHT = 36 //标题的高度--索引（A、B等）的高度
const NAME_HEIGHT = 50 //每行的高度---每个城市名称的高度



// 有房源的城市
const HOUSE_CITY = ['北京', '上海', '广州', '深圳']


export default class CityList extends React.Component {

    constructor(props) {
        super(props)
        // 状态值
        this.state = {
            cityList: {},
            cityIndex: [],
            activeIndex: 0
        }
        // 创建右侧导航序号的实例
        this.listComponent = React.createRef()
    }



    // 获取城市数据
    async getCityData() {
        // 获取所有城市信息
        const { data: res } = await getAreaCityApi()

        console.log(res,'返回数据');
        // 所有城市信息--进行格式化
        const { cityIndex, cityList } = formatCityData(res.body)

        // 获取热门城市数据
        const { data: hotCity } = await getAreaHotApi()
        // 将热门城市添加到城市列表数据中===并键名为  “hot”
        cityList['hot'] = hotCity.body
        // 将键名添加到键名中
        cityIndex.unshift('hot')

        // 获取当前定位城市
        const curCity = await getCurrentCity()
        // 将热门城市添加到城市列表数据中===并键名为  “hot”和[]的方式
        cityList['#'] = [curCity]
        cityIndex.unshift('#')

        // 设置状态值
        this.setState({
            cityList,
            cityIndex
        })
        console.log(cityIndex, cityList, '热门城市');
    }

    // 组件加载时回调
    async componentDidMount() {
        // 获取城市数据
        await this.getCityData()
        this.listComponent.current.measureAllRows()
    }

    // 渲染顶部NavBar
    renderNavBar = () => {
        return (

            <NavHeader>城市选择</NavHeader>
        )
    }
    // 渲染列表
    renderCityList = () => {
        return (
            <AutoSizer>
                {({ height, width }) => (
                    <List
                        height={height}
                        rowCount={this.state.cityIndex.length}
                        rowHeight={this.getRowHeight}
                        rowRenderer={this.rowRenderer}
                        width={width}
                        onRowsRendered={this.rowRendered}
                        ref={this.listComponent}
                        scrollToAlignment="start"
                    />
                )}
            </AutoSizer>
        )
    }

    // 创建动态计算每一行高度的方法
    getRowHeight = ({ index }) => {
        // 索引标题高度 + 城市数量 * 城市名称的高度
        // TITLE_HEIGHT + cityList[cityIndex[index]].length * NAME_HEIGHT
        const { cityList, cityIndex } = this.state
        return TITLE_HEIGHT + cityList[cityIndex[index]].length * NAME_HEIGHT
    }

    // 过滤数据
    // 封装处理字母索引的方法
    // 将#变成“当前定位”
    // 将hot变成“热门城市”
    // 将小写字母变成大写
    formatCityIndex = letter => {
        switch (letter) {
            case '#':
                return '当前定位'
            case 'hot':
                return '热门城市'
            default:
                return letter.toUpperCase()
        }
    }

    // 长列表
    rowRenderer = ({
        key, // Unique key within array of rows
        index, // Index of row within collection
        isScrolling, // The List is currently being scrolled
        isVisible, // This row is visible within the List (eg it is not an overscanned row)
        style, // Style object to be applied to row (to position it)
    }) => {
        const { cityIndex, cityList } = this.state
        const letter = cityIndex[index]
        return (
            <div
                key={key}
                style={style}
                className="city"
            >
                <div className="title">
                    {this.formatCityIndex(letter)}
                </div>
                {cityList[letter].map(item => {
                    return (
                        <div className="name" key={item.value} onClick={() => { this.changeCity(item) }}>{item.label}</div>
                    )
                })}</div>
        );
    }

    // 渲染右侧导航
    renderRightNav = () => {
        return (
            <ul className="city-index">
                {this.renderCityIndex()}
            </ul>
        )
    }
    // 点击改变房源地址
    changeCity = ({ label, value }) => {
        // 查找不否在有房源---有，就保存到本地
        if (HOUSE_CITY.indexOf(label) > -1) {
            localStorage.setItem('localCity', JSON.stringify({ label, value }))
            this.props.history.go(-1)
        } else {
            // 提示
            Toast.info('该城市暂无房源数据', 1, null, false)
        }
    }



    // 渲染右侧导航中的元素
    renderCityIndex = () => {
        return this.state.cityIndex.map((item, index) => {
            console.log(item, index);
            return (
                <li
                    className="city-index-item"
                    key={item}
                    onClick={() => {
                        // 拿到List组件的实例
                        this.listComponent.current.scrollToRow(index)
                        // console.log('index', index);
                    }}
                >
                    {/*判断一下，如果高亮状态的索引等于当前索引，那么就设置高亮样式*/}
                    <span className={this.state.activeIndex === index ? 'index-active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
                </li>
            )
        })

    }
    //  获取滚动时候,相应的数据
    rowRendered = ({ startIndex }) => {
        if (this.state.activeIndex !== startIndex) {
            this.setState({
                activeIndex: startIndex
            })
        }
    }

    render() {
        return (
            <div className="CityList">
                {/* 顶部导航 */}
                {this.renderNavBar()}
                {/* 城市列表 */}
                {this.renderCityList()}

                {/* 右侧导航 */}
                {this.renderRightNav()}
            </div>
        )
    }
}